package com.lvt.design.pattern.module.stat.v4;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 负责一定频率统计并发送到命令行
 *
 * @author LT
 * @date 2023年02月22日 22:40
 */
public class ConsoleReporter extends ScheduleReporter {

    private ScheduledExecutorService executorService;


    // 兼顾代码的易用性，新增一个封装了默认依赖的构造函数
    public ConsoleReporter() {
        this(new RedisMetricsStorage(), new Aggregator(), new ConsoleViewer());
    }

    public ConsoleReporter(MetricsStorage metricsStorage, Aggregator aggregator, StatViewer statViewer) {
        super(metricsStorage, aggregator, statViewer);
        this.executorService = Executors.newSingleThreadScheduledExecutor();
    }

    public void startRepeatedReport(long periodInSeconds, long durationInSeconds) {
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                long durationInMills = durationInSeconds * 1000;
                long endTimeInMills = System.currentTimeMillis();
                long startTimInMills = endTimeInMills - durationInMills;
                doStatAndReport(startTimInMills, endTimeInMills);
            }
        }, 0, periodInSeconds, TimeUnit.SECONDS);
    }
}
